package longrise.phone.com.bjjt_henan.widget;

import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.widget.RadioGroup;

/**
 * 自动换行的RadioGroup
 */
public class FlowRadioGroup extends RadioGroup {

    public FlowRadioGroup(Context context) {
        super(context);
    }

    public FlowRadioGroup(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int maxWidth = MeasureSpec.getSize(widthMeasureSpec);
        int x = 0;
        int y = 0;//计算的总高度
        int lineHeight = 0;//当前行累积计算的高度

        int childCount = getChildCount();
        for (int i = 0; i < childCount; i++) {
            final View child = getChildAt(i);
            if (child.getVisibility() != View.GONE) {
                measureChild(child, widthMeasureSpec, heightMeasureSpec);
                LayoutParams params = (RadioGroup.LayoutParams) child.getLayoutParams();
                int width = child.getMeasuredWidth() + params.leftMargin + params.rightMargin;
                int height = child.getMeasuredHeight() + params.topMargin + params.bottomMargin;
                x += width;
                if (x > maxWidth) {//超出一行的宽度
                    x = width;
                    y += lineHeight;
                    lineHeight = height;
                } else {
                    lineHeight = Math.max(lineHeight, height);
                }
            }
            //如果是最后一个，则计算出最后的值
            if (i == childCount - 1) {
                y += lineHeight;
            }
        }
        setMeasuredDimension(maxWidth, y);
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        final int count = getChildCount();
        int maxWidth = r - l;
        int x = 0;
        int y = 0;//计算的总高度
        int lineHeight = 0;//当前行累积计算的高度

        for (int i = 0; i < count; i++) {
            final View child = getChildAt(i);
            if (child.getVisibility() != View.GONE) {
                LayoutParams cParams = (RadioGroup.LayoutParams) child.getLayoutParams();
                int width = child.getMeasuredWidth() + cParams.leftMargin + cParams.rightMargin;
                int height = child.getMeasuredHeight() + cParams.topMargin + cParams.bottomMargin;

                x += width;
                if (x > maxWidth) {
                    x = width;
                    y += lineHeight;
                    lineHeight = height;
                } else {
                    lineHeight = Math.max(lineHeight, height);
                }
                child.layout(x - width + cParams.leftMargin, y + cParams.topMargin,
                        x - cParams.rightMargin, y + height - cParams.bottomMargin);
            }
        }
    }
}
